<?php

/**
 * 
 * Test zend cast form
 * @author damian 25-07-2012
 *
 */
class TestZendcastFormController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

	public function testAction()
    {
		echo 'dziala';
        // action body
    }
    
    
	public function preDispatch()
	{
	    $this->session = new Zend_Session_Namespace('default');
	
		if (! $this->session->items)
			$this->session->items = array();

		$this->currentItemId = count($this->session->items);
	}

	public function indexAction()
	{
		$this->view->items = $this->session->items;
	}

	public function createAction()
	{
		$this->view->form = new App_forms_ItemEditor($this->currentItemId ,$this->session, 'create');
		if ($this->getRequest()->isPost())
		{
		    if ($this->PostBack())
				$this->_helper->Redirector->gotoUrl('/item/');

		}
	
	}

	public function editAction()
	{
		$this->view->form = new App_forms_ItemEditor($this->getRequest()->getParam('id') ,$this->session, 'edit');

		if ($this->getRequest()->isPost())
		{
		    if ($this->PostBack())
				$this->_helper->Redirector->gotoUrl('/item/');

		}

		
	}

	public function deleteAction()
	{

		if (array_key_exists($this->getRequest()->getParam('id'), $this->session->items))
		{
			$this->session->items[$this->getRequest()->getParam('id')] = null;
			$this->view->message = 'item deleted!';
		}
		else
			$this->view->message = 'item not found!';

		

	}
	
	private function PostBack()
	{

		if ($this->view->form->isValid($this->getRequest()->getParams()))
		{
			//save the item
			$this->session->items[$this->view->form->getValue('id')] = $this->view->form->SaveItem();
			return true;
		}
		else
			$this->view->errorElements = $this->view->form->getMessages();

        return false;
	}

}

